package com.yoyo.common.core.constant;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Configuration
public class I18nConfig {
    // 语言映射表
    private static final Map<String, Locale> languageMapping = new HashMap<>();

    static {
        // 添加常见的语言代码映射
        languageMapping.put("zh", Locale.CHINESE);
        languageMapping.put("zh_cn", Locale.SIMPLIFIED_CHINESE);
        languageMapping.put("zh-cn", Locale.SIMPLIFIED_CHINESE);
        languageMapping.put("cn", Locale.SIMPLIFIED_CHINESE);
        languageMapping.put("en", Locale.ENGLISH);
        languageMapping.put("en_us", Locale.US);
        languageMapping.put("en-us", Locale.US);
        // 可以根据需要添加更多映射
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        localeResolver.setDefaultLocale(Locale.US);
        return new CustomLocaleResolver(localeResolver);
    }

    // 自定义LocaleResolver包装类
        private record CustomLocaleResolver(AcceptHeaderLocaleResolver delegate) implements LocaleResolver {

        @Override
            public Locale resolveLocale(jakarta.servlet.http.HttpServletRequest request) {
                String language = request.getHeader("Accept-Language");
                if (language != null) {
                    language = language.toLowerCase();
                    Locale mappedLocale = languageMapping.get(language);
                    if (mappedLocale != null) {
                        return mappedLocale;
                    }
                }
                return delegate.resolveLocale(request);
            }

            @Override
            public void setLocale(jakarta.servlet.http.HttpServletRequest request,
                                  jakarta.servlet.http.HttpServletResponse response,
                                  Locale locale) {
                delegate.setLocale(request, response, locale);
            }
        }
}
